<?php
session_start();
$lib_dir = str_ireplace("ajax", "lib", dirname(__FILE__));
require_once $lib_dir.'/config.php';
require_once $lib_dir.'/facebook.php';
require_once $lib_dir.'/util.php';
require_once $lib_dir.'/friend.php';
require_once $lib_dir.'/friends.php';

if(!isset($_REQUEST['mode']) || !ctype_digit($_REQUEST['mode'])){
    print('{ "error": "Missing or invalid required parameter" }');
    exit();
}

if(!isset($_SESSION['fb_'.FB_APP_ID.'_access_token'])){
    print('{ "error": "not connected to Facebook" }');
    exit();
}

$mode = $_REQUEST['mode'];

//check if there is data in session, otherwise keep going with fetching process
//if(isset($_SESSION["json_".$mode])){
//    
//    print($_SESSION["json_".$mode]);
//    
//}else{

    $facebook = new Facebook(array(
        'appId' => FB_APP_ID,
        'secret' => FB_APP_SECRET
    ));
    
    $user = $facebook->getUser();
    
    $friends = null;
    if($user){

            $now = time();	
        	
            $friends = array();
            $data = null;
            $error = 0;

/*
 * Test Code
 */
if($mode == 0){
    getError();
}
            
            //Messages
            $flag = ONEWAY_MESSAGE_FLAG + TWOWAY_MESSAGE_FLAG;
            if(($mode & $flag) === $flag){
                fetchAndProcessData($flag, &$friends, &$error, "getMessage", "processMessage");
            }
    
            //My Post
            $flag = MY_POST_FLAG;
            if(($mode & $flag) === $flag){
                fetchAndProcessData($flag, &$friends, &$error, "getMyPost", "processMyPost");
                          	
            }
        	//Friend Post
        	$flag = FRIEND_POST_FLAG;
            if(($mode & $flag) === $flag){
                fetchAndProcessData($flag, &$friends, &$error, "getFriendPost", "processFriendPost");
            }
    
            //Friend COMMENT ON STATUS 
            $flag = FRIEND_COMMENT_ON_STATUS_FLAG;
            if(($mode & $flag) === $flag){
                fetchAndProcessData($flag, &$friends, &$error, "getFriendCommentOnStatus", "processFriendCommentOnStatus");
            }
            
            //Friend COMMENT ON LINK 
            $flag = FRIEND_COMMENT_ON_LINK_FLAG;
            if(($mode & $flag) === $flag){
                fetchAndProcessData($flag, &$friends, &$error, "getFriendCommentOnLink", "processFriendCommentOnLink");
            }
    
            //Friend COMMENT ON NOTE 
            $flag = FRIEND_COMMENT_ON_NOTE_FLAG;
            if(($mode & $flag) === $flag){
                fetchAndProcessData($flag, &$friends, &$error, "getFriendCommentOnNote", "processFriendCommentOnNote");
            }
            
            //Friend COMMENT ON PHOTO
            $flag = FRIEND_COMMENT_ON_PHOTO_FLAG;
            if(($mode & $flag) === $flag){
                fetchAndProcessData($flag, &$friends, &$error, "getFriendCommentOnPhoto", "processFriendCommentOnPhoto");
            }
            
            //MY COMMENT ON STATUS
            $flag = MY_COMMENT_ON_STATUS_FLAG;
            if(($mode & $flag) === $flag){
                fetchAndProcessData($flag, &$friends, &$error, "getMyCommentOnStatus", "processMyCommentOnStatus");
            }
            
            //MY COMMENT ON LINK
            $flag = MY_COMMENT_ON_LINK_FLAG;
            if(($mode & $flag) === $flag){
                fetchAndProcessData($flag, &$friends, &$error, "getMyCommentOnLink", "processMyCommentOnLink");
            }
            
            //MY COMMENT ON NOTE
            $flag = MY_COMMENT_ON_NOTE_FLAG;
            if(($mode & $flag) === $flag){
                fetchAndProcessData($flag, &$friends, &$error, "getMyCommentOnNote", "processMyCommentOnNote");
            }
            
            //MY COMMENT ON PHOTO
            $flag = MY_COMMENT_ON_PHOTO_FLAG;
            if(($mode & $flag) === $flag){
                fetchAndProcessData($flag, &$friends, &$error, "getMyCommentOnPhoto", "processMyCommentOnPhoto");
            }
            
            //Friend LIKE ON STATUS
            $flag = FRIEND_LIKE_ON_STATUS_FLAG; 
            if(($mode & $flag) === $flag){
                fetchAndProcessData($flag, &$friends, &$error, "getFriendLikeOnStatus", "processFriendLikeOnStatus");
            }
            
            //Friend LIKE ON LINK 
            $flag = FRIEND_LIKE_ON_LINK_FLAG;
            if(($mode & $flag) === $flag){
                fetchAndProcessData($flag, &$friends, &$error, "getFriendLikeOnLink", "processFriendLikeOnLink");
            }
    
            //Friend LIKE ON NOTE
            $flag = FRIEND_LIKE_ON_NOTE_FLAG; 
            if(($mode & $flag) === $flag){
                fetchAndProcessData($flag, &$friends, &$error, "getFriendLikeOnNote", "processFriendLikeOnNote");
            }
            
            //Friend LIKE ON PHOTO
            $flag = FRIEND_LIKE_ON_PHOTO_FLAG; 
            if(($mode & $flag) === $flag){
                fetchAndProcessData($flag, &$friends, &$error, "getFriendLikeOnPhoto", "processFriendLikeOnPhoto");
            }
            
           
            //MY LIKE ON STATUS
            $flag = MY_LIKE_ON_STATUS_FLAG;
            if(($mode & $flag) === $flag){
                fetchAndProcessData($flag, &$friends, &$error, "getMyLikeOnStatus", "processMyLikeOnStatus");
            }
            
            //MY LIKE ON LINK
            $flag = MY_LIKE_ON_LINK_FLAG;
            if(($mode & $flag) === $flag){
                fetchAndProcessData($flag, &$friends, &$error, "getMyLikeOnLink", "processMyLikeOnLink");
            }
            
            //MY LIKE ON NOTE
            $flag = MY_LIKE_ON_NOTE_FLAG;
            if(($mode & $flag) === $flag){
                fetchAndProcessData($flag, &$friends, &$error, "getMyLikeOnNote", "processMyLikeOnNote");
            }
            
            //MY LIKE ON PHOTO
            $flag = MY_LIKE_ON_PHOTO_FLAG;
            if(($mode & $flag) === $flag){
                fetchAndProcessData($flag, &$friends, &$error, "getMyLikeOnPhoto", "processMyLikeOnPhoto");
            }
        
        	//sort
        	if(is_array($friends)){
        	    uasort($friends, 'cmp');
        	}    
    		
        	/*
        	 *  Build up JSON string
        	 */
            $json = '{';
            $json .= '"mode":'.$mode.',';
            $json .= '"data":';
            $json .= '{';
        
            $isFirst = true;
            foreach($friends as $f){
                //only if friend who has at least one communication
                if($f->getNumberOfAllCommunications() > 0){
                    if(!$isFirst){
                        $json .= ',';
                    }
                    $json .= '"'.$f->getfId().'":{';
//                    $json .= '"fId" : "'.$f->getfId().'"';
//                    $json .= ',"count":{';
                    
                    $isFirstSub = true;
                    foreach ($data_type_flags as $flag => $flagMode) {
                        if($f->getNumberOfData($flag) > 0){
                            if(!$isFirstSub){
                                $json .= ',';
                            }
                            $json .= '"'.$flagMode.'" : "'.$f->getNumberOfData($flag).'"';
                            $isFirstSub = false;
                        }
                        
                    }
//                    $json .= '}'; //count
                    $json .= '}'; //friend object
                    $isFirst = false;
                }
            }
        
            $json .= "}";
            
            if($error > 0){
                $json .= ',"error":';
                $json .= '"'.$error.'"';
            }
            
            $json .= '}';
            
            //use session as cache
            if($error == 0){
                $_SESSION["json_".$mode] = $json;
            }
    
            //return output
            print $json;

//log report

$log = "Hashed UID:".md5($_SESSION['fb_'.FB_APP_ID.'_access_code']['uid']).",Tried Mode:".$mode.", Error:".$error.",Elapsed Time:".(time() - $now)."\n";
file_put_contents("../log/report_".date('Y_m_d').".txt", $log, FILE_APPEND);
//        } catch (FacebookApiException $e){
//            error_log("getAllDataFromFQL() error : ".(time() - $now));
//            print('{"error":"'."Facebook error:".$e->getMessage().'"}');
//        }
//    }
}
